import { KcpdFuncs } from "@/kcpd/func";
import { KcpdWatingState } from "@/kcpd/watingState";
import { DisplaySlotId, Player, world } from "@minecraft/server";
import { PlayerGroupSet } from "@sapi-game/gamePlayer/groupSet";
import { AutoStopState } from "@sapi-game/gameState/common/autoStop";
import { HideAndSeekConfig, HideAndSeekContext } from "./context";
import { HideAndSeekMainState } from "./mainState";
import { HideAndSeekModule } from "./module";
import { HideAndSeekPlayer } from "./player";

export class HideAndSeekGame extends HideAndSeekModule.Engine<
    HideAndSeekConfig & { players: Player[] }
> {
    protected override buildContext(
        config: HideAndSeekConfig & { players: Player[] }
    ): HideAndSeekContext {
        const group = this.groupBuilder.fromPlayers(config.players);
        return new HideAndSeekContext(config, group);
    }

    override onStart(): void {
        this.pushState(KcpdWatingState, {
            players: this.context.players,
            next: () => {
                this.resetState(HideAndSeekMainState);
                this.pushState(AutoStopState<HideAndSeekPlayer>, {
                    groupSet: new PlayerGroupSet([this.context.players]),
                    onLeave: (p) => {
                        this.context.players.sendMessage(
                            `${p.name} 离开了当前游戏`
                        );
                        p.alive = false;
                    },
                });
            },
        });
    }

    override onStop(): void {
        world.scoreboard.clearObjectiveAtDisplaySlot(DisplaySlotId.Sidebar);
        this.context.players.forEach((p) => {
            KcpdFuncs.hub(p.player);
        });
        KcpdFuncs.reloadDoor();
    }
}
